package HTML::FormFu::Element::Dojo::Editor2;

use strict;
use warnings;
use base 'HTML::FormFu::Element::Textarea';

use HTML::FormFu::Util qw( append_xml_attribute );

__PACKAGE__->mk_attrs(qw/ dojo_attributes /);

sub prepare_id {
    my ( $self, $render ) = @_;
    
    if ( !defined $self->id && !defined $self->auto_id ) {
        $self->auto_id("%f_%n");
    }

    $self->SUPER::prepare_id($render);
    
    return;
}

sub prepare_attrs {
    my ( $self, $render ) = @_;
    
    # add textarea class, so we don't have to change css for default layout
    append_xml_attribute(
        $render->{container_attributes}, 'class', 'textarea'
    );
    
    return;
}

sub render {
    my $self = shift;

    my $render = $self->SUPER::render(@_);
 
    my %attr = %{ $self->dojo_attributes };
    
    my $optstr = join ", ", map {
        sprintf qq{%s: "%s"}, $_, $attr{$_}
    } sort keys %attr;
    
    my $id = $render->id;
    my $js = $render->{javascript};
    $js = "" if !defined $js;
    
    $js .= <<EOF;
dojo.require("dojo.widget.Editor2");
dojo.widget.createWidget(
    "Editor2",
    {$optstr},
    dojo.byId("$id")
);
EOF

    $render->{javascript} = $js;
    
    return $render;
}

1;
